#!/usr/bin/perl
#Programmer: Rory Carmichael
#Purpose: splice peak data into multiple alignments
#Requires multiple-alignments to be fasta formatted, 1 line per sequence
#Usage: better-alignment-splice.pl <window size> <alignment> [<peakfile1> <peakfile2> <peakfile3> ... <peakfileN>]

use POSIX;

my ($w_size, $aln, @peakfiles) = @ARGV;
if($#ARGV < 2) {
	print STDERR "Usage: better-alignment-splice.pl <window size> <alignment> [<peakfile1> <peakfile2> ... <peakfileN>]\n";
	exit 1;
}

sub trim_ends() {
	my ($wsize, $seq) = @_;
	if ($wsize == 0) {
		return $seq;
	} elsif ($wsize % 2 == 0 || $wsize  == 1) {
		die("Invalid window size: $wsize ... Window size must be an odd number > 1.");
	} 
	my $endtrim = floor($wsize/2);
	return substr($seq,$endtrim, -1*$endtrim);
}

sub get_ids() {
	my ($fname, $idhashref) = @_;
	my $count = 0;
	open(IF, "$fname");
	while (my $line = <IF>) {
		chomp $line;
		if ($line =~ /^>/) {
			$idhashref->{$line} = <IF>;
			chomp $idhashref->{$line};
			$count++;
		}
	}
	close(IF);
	return $count;
}

sub splice_seq() {
	my ($wsize, $seq, $peaks, $sub_char) = @_;
	if (($wsize % 2 == 0 && $wsize != 0) || $wsize == 1) {
		die("Invalid window size: $wsize ... Window size must be an odd number > 1.");
	}
	$sub_char = "-" unless (defined($sub_char));
	$endtrim = floor($wsize/2);

	my @seq_a = split('',$seq);
	my @peak_a = split(',', $peaks);
	#Pad peak sequence to adjust for sliding window
	for (my $i=0;$i<$endtrim;$i++) {
		unshift(@peak_a,$sub_char);
		push(@peak_a,$sub_char);
	}
#	print STDERR "Splicing sequence of length " . scalar(@seq_a) . " with stuff of length " . scalar(@peak_a) . "\n";
	my $clean_seq = $seq;
	$clean_seq =~ s/-//g;
	if (scalar(@peak_a) != scalar(split('',$clean_seq))) {
		my $cl_out = join("\t", split('',$clean_seq)) . "\n";
		my $s_out = join("\t", @peak_a) . "\n";
		die("ERROR: Gapless sequence length does not match splice length\n$cl_out$s_out");
	}
	my @splice_a = ();
	foreach my $char (@seq_a) {
		if ($char eq "-") {
			push(@splice_a, $char);
		} else {
			if (scalar(@peak_a) == 0) {
				push(@splice_a, '-');
			} else {
				my $dist = shift @peak_a;
				push(@splice_a, $dist);
			}
		}
	}
#	print STDERR "Ended up with splice of length " . scalar(@splice_a) . "\n";
	my $retlink = \@splice_a;
	return $retlink;
}

my %idhash = ();
my %finalhash = ();
my $idcount = &get_ids($aln, \%idhash);
my $len = 0;
foreach my $file (@peakfiles) {
	open(IF, "$file");
	while (my $line = <IF>) {
		chomp $line;
		if ($line =~ /^>/) {
			if(exists($idhash{$line})) {
				my $peaks = <IF>;
				chomp $peaks;
				$finalhash{$line} = &splice_seq($w_size, $idhash{$line}, $peaks);
				if (scalar(@{$finalhash{$line}}) > $len) {
					$len = scalar(@{$finalhash{$line}});
				}
			}
		}
	}
	close(IF);
}
print "#" . join("\t", keys(%finalhash)) . "\n";
print "#\n";
for (my $i=0; $i<$len;$i++) {
	my @newrow = ();
	foreach my $key (sort(keys(%finalhash))) {
		push(@newrow,$finalhash{$key}->[$i]);
	}
	print join("\t",@newrow) . "\n";
}
